package cn.slipi.admin.common.utils.validation;

import cn.slipi.admin.common.exception.base.BizException;
import cn.slipi.admin.common.utils.validation.constrations.InEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 枚举值校验
 *
 * @author lee
 * @date 2019/1/22
 * @since 1.0.0
 */
public class EnumValidator implements ConstraintValidator<InEnum, Object>, Annotation {

    private Logger LOG = LoggerFactory.getLogger(EnumValidator.class);

    private List<Object> values = new ArrayList<>();

    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }

    @Override
    public void initialize(InEnum inEnum) {
        Class<?> clz = inEnum.value();
        Object[] objects = clz.getEnumConstants();
        try {
            Method method = clz.getMethod("getValue");
            if (Objects.isNull(method)) {
                throw new BizException(400, String.format("枚举对象{}缺少字段名为value的字段", clz.getName()));
            }
            Object value = null;
            for (Object obj : objects) {
                value = method.invoke(obj);
                values.add(value);
            }
        } catch (Exception e) {
            LOG.error("[处理枚举校验异常]", e);
        }
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        return Objects.isNull(o) || values.contains(o);
    }
}
